import { message } from "ant-design-vue"
import { useUserStore } from "./user"
import type { Exposed as VideoPreviewModalExposed } from '@/components/VideoPreviewModal/type'

type LoadingState = {
    spinning: boolean
    tip?: string
    _n: number
}
type LogoutState = {
    open: boolean
}
export const useAppStore = defineStore("app", () => {
    const loading = ref<LoadingState>({ spinning: false, _n: 0 })
    function toggleLoading(spinning: boolean, tip?: string): void {
        if (spinning) {
            loading.value._n += 1
        } else if (loading.value._n > 0) {
            loading.value._n -= 1
        }
        loading.value.spinning = loading.value._n !== 0
        if (tip && !loading.value.tip) {
            loading.value.tip = tip
        }
        if (!loading.value.spinning) {
            loading.value.tip = void 0
        }
    }
    const logoutState = ref<LogoutState>({
        open: false
    })
    function openLogout() {
        logoutState.value.open = true
    }
    async function handleLogout() {
        const userStore = useUserStore()
        await userStore.logout()
        logoutState.value.open = false
        message.success('已退出登录')
        toLogin()
    }
    const compRefs = markRaw({
        VideoPreviewModalRef: ref<INullable<VideoPreviewModalExposed>>(null),
    })
    return {
        loading,
        toggleLoading,
        logoutState,
        openLogout,
        handleLogout,
        compRefs
    }
})